const utils = require('./utils');
const mfs = require('./mfs');

function pack(config) {
    let appABIs = null;
    for (let i = 0; i < config.appABIs.length; i++) {
        if (null == appABIs) {
            appABIs = '['
        } else {
            appABIs += ','
        }
        appABIs += '\'' + config.appABIs[i] + '\'';
    }
    appABIs += ']';

    let enginePath = config.enginePath;
    if (utils.isMac()) {
        enginePath += '/MacOS/CocosCreator';
    } else if (utils.isWindows()) {
        enginePath += '/CocosCreator.exe'
    }

    let cmd = enginePath +
        ' --path ' + config.path +
        ' --build title=' + config.title +
        ';packageName=' + config.packageName +
        ';apiLevel=' + config.apiLevel +
        ';appABIs=' + appABIs +
        ';xxteaKey=' + config.xxteaKey +
        ';template=link;platform=android;debug=false;inlineSpriteFrame=false;mergeStartScene=false;optimizeHotUpdate=false;useDebugKeystore=true;md5Cache=false;encryptJs=true;zipCompressJs=true;'
    return utils.runSh(cmd);
}

module.exports.pack = pack;

const url = '';
function generator(config) {
    let manifest = {};
    const dirInfo = mfs.parse(config.dirPath);
    manifest.packageUrl = url + '/' + dirInfo.base + '/';
    manifest.remoteManifestUrl = manifest.packageUrl + 'project.manifest';
    manifest.remoteVersionUrl = manifest.packageUrl + 'version.manifest';
    manifest.version = config.version;

    const destVersion = mfs.join(config.dirPath, 'version.manifest');
    mfs.writeFile(destVersion, JSON.stringify(manifest, null, 4));// 写入基本信息到version.manifest

    manifest.assets = {};
    const paths = mfs.readDir(config.dirPath);

    let manifestPath = '';
    paths.forEach(filePath => {
        const relative = encodeURI(mfs.relative(config.dirPath, filePath).replace(/\\/g, '/'));
        if (mfs.extname(filePath) === '.manifest') { // manifest 不进行更新
            manifestPath = relative;
            return;
        }
        manifest.assets[relative] = {
            size: mfs.size(filePath),
            md5: utils.md5(mfs.readFile(filePath, 'binary'))
        };
        const compressed = mfs.extname(filePath).toLowerCase() === '.zip';
        if (compressed) {
            manifest.assets[relative].compressed = true;
        }
    });
    const destManifest = mfs.join(config.dirPath, 'project.manifest');
    mfs.writeFile(destManifest, JSON.stringify(manifest, null, 0));
    return {
        manifest: manifest,
        path: manifestPath
    }

}
module.exports.generator = generator;